package leetcode.editor.cn;

/**
 * @author: yangwk
 * @date: 2023/10/19
 * @description:
 **/
public class P482 {
    public static void main(String[] args) {
        System.out.println(licenseKeyFormatting("2-gq-aa", 2));
    }

    /**
     * You are given a license key represented as a string s that consists of only alphanumeric characters and dashes.
     * The string is separated into n + 1 groups by n dashes. You are also given an integer k.
     * <p>
     * We want to reformat the string s such that each group contains exactly k characters,
     * except for the first group, which could be shorter than k but still must contain at least one character.
     * Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
     * <p>
     * Return the reformatted license key.
     */
    public static String licenseKeyFormatting(String s, int k) {
        StringBuilder result = new StringBuilder();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = Character.toUpperCase(s.charAt(i));
            if (c == '-') {
                if (stringBuilder.length() < k) {
                    continue;
                }
                result.append(stringBuilder + "-");
                stringBuilder = new StringBuilder();
            } else {
                if (stringBuilder.length() == k) {
                    result.append(stringBuilder + "-");
                    stringBuilder = new StringBuilder();
                }
                stringBuilder.append(c);

            }
        }
        if (stringBuilder.length() != 0) {
            result.append(stringBuilder + "-");
        }
        if (result.length() == 0) {
            return result.toString();
        }
        return result.reverse().substring(1);
    }
}
